package logic

import (
	"erp/model"
	"fmt"
	"strings"

	"gorm.io/gorm"
)

type ProductService struct{ DB *gorm.DB }

func (s ProductService) List() ([]model.Product, error) {
	var list []model.Product
	if err := s.DB.Find(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}

func (s ProductService) Get(id uint) (*model.Product, error) {
	var p model.Product
	if err := s.DB.First(&p, id).Error; err != nil {
		return nil, err
	}
	return &p, nil
}

func (s ProductService) Create(p *model.Product) error {
	// 生成产品编码
	if p.Code == "" {
		p.Code = s.generateProductCode(p.Name)
	}
	return s.DB.Create(p).Error
}

func (s ProductService) Update(id uint, in *model.Product) (*model.Product, error) {
	var p model.Product
	if err := s.DB.First(&p, id).Error; err != nil {
		return nil, err
	}

	// 更新字段
	if in.Name != "" {
		p.Name = in.Name
	}
	if in.Code != "" {
		p.Code = in.Code
	}
	if in.Price > 0 {
		p.Price = in.Price
	}
	if in.Stock >= 0 {
		p.Stock = in.Stock
	}
	if in.Unit != "" {
		p.Unit = in.Unit
	}
	if in.Category != "" {
		p.Category = in.Category
	}
	if in.Description != "" {
		p.Description = in.Description
	}
	if in.MinStock >= 0 {
		p.MinStock = in.MinStock
	}

	if err := s.DB.Save(&p).Error; err != nil {
		return nil, err
	}
	return &p, nil
}

func (s ProductService) Delete(id uint) error {
	return s.DB.Delete(&model.Product{}, id).Error
}

// 库存调整
func (s ProductService) AdjustStock(id uint, quantity int, stockType string, notes string) error {
	var product model.Product
	if err := s.DB.First(&product, id).Error; err != nil {
		return fmt.Errorf("产品不存在: %w", err)
	}

	switch stockType {
	case "in":
		product.Stock += quantity
	case "out":
		if product.Stock < quantity {
			return fmt.Errorf("库存不足，当前库存: %d, 需要: %d", product.Stock, quantity)
		}
		product.Stock -= quantity
	default:
		return fmt.Errorf("无效的库存调整类型: %s", stockType)
	}

	return s.DB.Save(&product).Error
}

// 产品搜索
func (s ProductService) Search(query string) ([]model.Product, error) {
	var products []model.Product
	query = strings.TrimSpace(query)

	err := s.DB.Where("name LIKE ? OR code LIKE ? OR category LIKE ?",
		"%"+query+"%", "%"+query+"%", "%"+query+"%").
		Find(&products).Error

	return products, err
}

// 生成产品编码
func (s ProductService) generateProductCode(name string) string {
	if len(name) == 0 {
		return "P001"
	}

	// 简单的编码生成逻辑
	prefix := strings.ToUpper(string(name[0]))
	var count int64
	s.DB.Model(&model.Product{}).Where("code LIKE ?", prefix+"%").Count(&count)

	return fmt.Sprintf("%s%03d", prefix, count+1)
}
